<template>
  <a-modal
    v-model:visible="props.otherShowble"
    width="100vw"
    :title="`${isBatchHasObj.tmbh || ''}${isBatchHasObj.tmbt || ''}评阅标准设置`"
    @cancel="emit('update:otherShowble', false)"
    @ok="editOk"
    :style="{
      maxWidth: '100vw',
      top: '0px',
    }"
    :bodyStyle="{
      height: 'calc(100vh - 102px)',
      backgound: 'rgba(255,255,255,1)',
    }"
  >
    <a-form
      class="cancel-form"
      :selfUpdate="true"
      :rules="rules"
      ref="setForm"
      :model="editabDataChead"
    >
      <a-row :gutter="[10, 20]">
        <a-col :span="4">
          <a-form-item>
            <span class="text-red-600"> 温馨提示:批量设置会覆盖子题设置 </span>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="试题类型">
            <span>{{ isBatchHasObj.tmlx }}</span>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="试题总分值:" name="tmfz">
            <span>{{ isBatchHasObj.tmfz }}</span>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="试题最小得分单位:">{{ editabDataChead.pydfgc ?? '--' }}</a-form-item>
        </a-col>
        <a-col :span="24"></a-col>
        <a-col :span="4" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
          <a-form-item label="评阅模式" name="pyMs">
            <a-select
              :options="pymsOptions"
              v-model:value="editabDataChead.pyMs"
              :disabled="machineReadableProblem.includes(isBatchHasObj.tmlx)"
              :autoClearSearchValue="false"
              style="width: 100%"
              placeholder="请选择评阅模式"
            />
          </a-form-item>
        </a-col>
        <a-col :span="4" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
          <a-form-item label="最小得分单位" name="pydfgc">
            <a-input
              placeholder="最小得分单位"
              type="number"
              step="0.5"
              style="width: 100%"
              min="0.5"
              :disabled="statuTypeBloon"
              v-model:value="editabDataChead.pydfgc"
            />
          </a-form-item>
        </a-col>
        <a-col :span="4" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
          <a-form-item label="自评允许最大分差(含)" name="zpFc">
            <a-input
              placeholder="自评允许最大分差(含),0代表不进行自评校验"
              step="0.5"
              type="number"
              style="width: 100%"
              min="0"
              :disabled="statuTypeBloon"
              v-model:value="editabDataChead.zpFc"
            />
          </a-form-item>
        </a-col>
        <a-col
          :span="4"
          v-if="editabDataChead.pyMs == '2' && !machineReadableProblem.includes(isBatchHasObj.tmlx)"
        >
          <a-form-item label="双评分差(含)" name="spFc">
            <a-input
              type="number"
              placeholder="双评分差"
              :disabled="statuTypeBloon"
              style="width: 100%"
              step="0.5"
              min="0"
              v-model:value="editabDataChead.spFc"
            />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item
            label="漏选是否得分"
            name="dxlxScoreType"
            v-if="isBatchHasObj.tmlx == '多项选择题'"
          >
            <a-select
              v-model:value="editabDataChead.dxlxScoreType"
              :options="dxlxOptions"
              style="width: 100%"
              placeholder="请选择"
            />
          </a-form-item>
        </a-col>
        <a-col
          :span="4"
          v-if="isBatchHasObj.tmlx == '多项选择题' && editabDataChead.dxlxScoreType == 'CUSTOM'"
        >
          <a-form-item label="漏选得分" name="dxlxCustomScore">
            <a-input
              placeholder="漏选得分"
              step="0.5"
              style="width: 100%"
              min="0.5"
              v-model:value="editabDataChead.dxlxCustomScore"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="!machineReadableProblem.includes(isBatchHasObj.tmlx)">
          <a-form-item label="评阅教师" name="pySzJsfpAccountList">
            <a-select
              v-model:value="editabDataChead.pySzJsfpAccountList"
              mode="multiple"
              :disabled="machineReadableProblem.includes(isBatchHasObj.tmlx)"
              :options="teacherOptions"
              :filter-option="filterOption"
              show-search
              placeholder="请选择（可按工号搜索）"
            />
          </a-form-item>
        </a-col>
        <a-col :span="isMinimumUnit ? 6 : 24">
          <a-row :gutter="10">
            <a-col
              :span="isMinimumUnit ? 24 : 6"
              v-for="(item, index) in editabDataChead.pySzCkdaInfoList"
              :key="index"
            >
              <a-form-item
                :label="item.name"
                :class="isMinimumUnit || isBatchHasObj.tmlx == '填空题' ? 'cancel-form-item' : ''"
                :name="['pySzCkdaInfoList', index, 'ckda']"
                :rules="{ required: true, message: '答案不能为空', trigger: 'change' }"
              >
                <span
                  v-if="
                    machineReadableProblem.includes(isBatchHasObj.tmlx) ||
                    isBatchHasObj.tmlx === '填空题'
                  "
                  class="mx-2 text-[14px] text-red-600"
                >
                  ({{ item.tmfz }}分)
                </span>
                <a-checkbox-group
                  v-if="isBatchHasObj.tmlx == '多项选择题'"
                  v-model:value="item.ckda"
                  width="100%"
                >
                  <a-row :gutter="10">
                    <a-col :span="4" v-for="da in item.ckdaOptions" :key="da.value">
                      <a-checkbox :value="da.value" style="line-height: 32px">
                        {{ da.label }}
                      </a-checkbox>
                    </a-col>
                  </a-row>
                </a-checkbox-group>
                <a-radio-group
                  v-else-if="machineReadableProblem.includes(isBatchHasObj.tmlx)"
                  v-model:value="item.ckda"
                >
                  <a-radio :value="da.value" v-for="da in item.ckdaOptions" :key="da.value">{{
                    da.label
                  }}</a-radio>
                </a-radio-group>
                <Tinymce
                  v-else
                  v-model="item.ckda"
                  @click="previewImg"
                  :height="isBatchHasObj.tmlx == '填空题' ? 100 : 185"
                  :showImageUpload="isBatchHasObj.tmlx == '填空题' ? false : true"
                  :sjlb="chartObj.sjlb"
                  :kmdm="props.kmdm"
                  :stid="item.stId"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-col :span="18" v-if="isMinimumUnit || isBatchHasObj.tmlx == '填空题'">
          <a-form-item label="得分点设置" class="!mb-8px"></a-form-item>
          <a-table
            rowKey="stId"
            :dataSource="editabDataChead.pySzDfdList"
            :columns="scoreColumn"
            class="tablstyle"
            bordered
            bodyCell
            :pagination="false"
            size="small"
          >
            <template #headerCell="{ column }">
              <template v-if="column.key === 'handle'">
                <span> 操作 </span>
                <a-button
                  type="primary"
                  size="small"
                  style="margin: 0 0 0 10px"
                  :disabled="
                    (!!isBatchHasObj.childList && !!isBatchHasObj.childList.length) ||
                    isBatchHasObj.jdFlag == 'y' ||
                    statuTypeBloon
                  "
                  class="!text-12px"
                  @click="handelscoreCancel"
                >
                  新增得分点
                </a-button>
              </template>
            </template>
            <template #bodyCell="{ column, record, index }">
              <a-form-item
                :name="[`pySzDfdList`, index, column.key]"
                :rules="{
                  required: true,
                  validator: validatoFun,
                  trigger: 'blur',
                }"
                v-if="['contents', 'dfdScore', 'sortNum'].includes(column.dataIndex)"
              >
                <a-input
                  :placeholder="column.title"
                  :type="column.dataIndex == 'contents' ? 'text' : 'number'"
                  :step="column.dataIndex == 'dfdScore' ? 0.5 : 1"
                  :min="column.dataIndex == 'dfdScore' ? 0.5 : ''"
                  style="width: 100%"
                  v-model:value="record[column.key]"
                />
              </a-form-item>
              <a-button
                danger
                type="link"
                v-if="column.key === 'handle'"
                :disabled="statuTypeBloon"
                @click="handelstoreDetale(record, index)"
              >
                删除
              </a-button>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { machineReadableProblem, isJdWrongType, isJdCorrectType } from '../index'
import { ref, watch, computed, onMounted, h } from 'vue'
import { Tinymce } from '/@/components/Tinymce'
import { cloneDeep } from 'lodash-es'

import { createImgPreview } from '/@/components/Preview'
// api
import { getHasTeachee } from '/@/api/organization/subjectManage'
import { reviewbatchHandlePySzbz, reviewGetPySzInfoByStId } from '/@/api/examinationAudit'

import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage, createConfirm } = useMessage()

// 最小试题
const isMinimumUnit = computed(() => {
  return !props.isBatchHasObj.children || !props.isBatchHasObj.children.length
})

// 表达校验提交
const setForm = ref()
function editOk() {
  if (
    props.sysConfig.bigScoreCutFlag &&
    props.sysConfig.bigScoreValue < props.isBatchHasObj.tmfz &&
    editabDataChead.value.pySzDfdList.length == 0 &&
    !isJdCorrectType(props.isBatchHasObj)
  )
    return createMessage.error('得分点设置不能为空')
  if (editabDataChead.value.pySzDfdList?.length && !isJdCorrectType(props.isBatchHasObj)) {
    let numAll = editabDataChead.value.pySzDfdList.reduce(
      (a, b) => a + (Number(b.dfdScore) || 0),
      0
    )
    if (numAll != props.isBatchHasObj.tmfz) return createMessage.error('得分点分值和总分不一致')
  }

  setForm.value
    .validate()
    .then(async () => {
      let form = JSON.parse(JSON.stringify(editabDataChead.value))
      if (props.isBatchHasObj.tmlx == '多项选择题') {
        for (let i = 0; i < form.pySzCkdaInfoList.length; i++) {
          form.pySzCkdaInfoList[i].ckda = form.pySzCkdaInfoList[i].ckda.join(',')
        }
      }
      let { code, message } = await reviewbatchHandlePySzbz({
        ...form,
        stId: props.isBatchHasObj.id,
        kmdm: props.kmdm,
      })
      if (code == 200) {
        createMessage.success('操作成功')
        emit('update:otherShowble', false)
        emit('successFun')
      } else {
        createMessage.error(message)
      }
    })
    .catch(err => console.error(err))
}

const emit = defineEmits(['update:otherShowble', 'update:isBatchHasObj', 'successFun'])
const props = defineProps({
  isBatchHasObj: {
    type: Object,
    default: () => ({}),
  },
  otherShowble: {
    type: Boolean,
    dafault: false,
  },
  statuTypeBloon: {
    type: Boolean,
    default: false,
  },
  kmdm: {
    type: String,
    default: '',
  },
  sysConfig: {
    type: Object,
    default: () => ({}),
  },
  chartObj: {
    type: Object,
    default: () => ({}),
  },
})

async function validatoFun(rule, value) {
  if (!value) {
    return Promise.reject('请输入')
  } else if (rule.field.indexOf('dfdScore') > -1) {
    if (value % editabDataChead.value.pydfgc !== 0) {
      return Promise.reject('得分点分值必须为最小得分单位的整数倍')
    } else if (props.isBatchHasObj.tmfz < value) {
      return Promise.reject('得分点分值不能大于题目分值')
    } else if (props.sysConfig.bigScoreCutFlag && props.sysConfig.bigScoreValue < value) {
      return Promise.reject('得分点分值不能大于大分值分片')
    }
  }
}

const rules = {
  pyMs: [{ required: true, message: '评阅模式不能为空', trigger: 'blur' }],
  pydfgc: [
    {
      required: true,
      validator: async ({}, value) => {
        if (!value) {
          return Promise.reject('最小得分单位不能为空')
        } else if (value % 0.5 !== 0) {
          return Promise.reject('最小得分单位是0.5的倍数')
        } else if (props.isBatchHasObj.tmfz < value) {
          return Promise.reject('最小得分单位不能大于试题分值')
        } else if (props.isBatchHasObj.tmfz % value !== 0) {
          return Promise.reject('试题分值必须为最小得分单位的整数倍')
        } else if (props.sysConfig.bigScoreCutFlag && props.sysConfig.bigScoreValue < value) {
          return Promise.reject('最小得分单位不能大于大分值分片')
        }
      },
      trigger: 'blur',
    },
  ],
  dxlxCustomScore: [
    {
      required: true,
      validator: async ({}, value) => {
        if (!value) {
          return Promise.reject('漏选得分不能为空')
        } else if (value % 0.5 !== 0) {
          return Promise.reject('漏选得分是0.5的倍数')
        } else if (props.isBatchHasObj.tmfz / props.isBatchHasObj.children.length <= value) {
          return Promise.reject('漏选得分不能大于试题分值')
        }
      },
      trigger: 'blur',
    },
  ],
  dxlxScoreType: [{ required: true, message: '多选题漏选得分类型不能为空', trigger: 'blur' }],
  zpFc: [
    {
      required: true,
      validator: async ({}, value) => {
        if (!value) {
          return Promise.reject('自评允许最大分差(含)需大于零')
        } else if (props.isBatchHasObj.tmfz / 2 < value) {
          return Promise.reject('自评允许最大分差(含)不能大于试题分值一半')
        }
      },
      trigger: 'blur',
    },
  ],
  spFc: [
    {
      required: true,
      validator: async ({}, value) => {
        if (!value) {
          return Promise.reject('双评分差需大于零')
        } else if (props.isBatchHasObj.tmfz / 2 < value) {
          return Promise.reject('双评分差不能大于试题分值一半')
        }
      },
      trigger: 'blur',
    },
  ],
  pySzJsfpAccountList: [{ required: true, message: '不能为空', trigger: 'blur' }],
}

const scoreColumn = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    customRender: ({ index }) => {
      return (index += 1)
    },
    width: 60,
    fixed: true,
  },
  {
    title: '得分点',
    dataIndex: 'contents',
    key: 'contents',
  },
  {
    title: '分值',
    key: 'dfdScore',
    dataIndex: 'dfdScore',
    width: 90,
    align: 'center',
  },
  {
    title: '排序',
    key: 'sortNum',
    dataIndex: 'sortNum',
    width: 90,
    align: 'center',
  },
  {
    title: '操作',
    key: 'handle',
    align: 'center',
    width: 160,
    fixed: 'right',
  },
]

// 提交表单
const editabDataChead = ref<any>({
  pyMs: '1',
  pySzCkdaInfoList: [],
  pySzDfdList: [],
})

// 机读题答案选择

const pySzInfoVO = ref<any>({})
const teacherOptions = ref<any[]>([])

/**
 * 评阅模式
 */
const pymsOptions = ref<any[]>([])

/**
 * 漏选得分类型
 */
const dxlxOptions = ref<any[]>([])

//查询可分配教师

const getTeacherOptions = async val => {
  let { code, data } = await getHasTeachee({
    kmdm: props.kmdm,
    jsxm: val,
  })
  if (code == 200) {
    for (let key in data) {
      teacherOptions.value.push({
        label: `${data[key]}(${key})`,
        value: key,
      })
    }
  }
}

function filterOption(input: string, option: any = {}) {
  return option['label']?.indexOf(input) >= 0
}

// 删除得分点
const handelstoreDetale = async ({}, index) => {
  createConfirm({
    iconType: 'warning',
    title: () => h('span', '温馨提醒'),
    content: () => h('span', '您确定删除得分点吗？'),
    onOk: async () => {
      editabDataChead.value.pySzDfdList.splice(index, 1)
    },
  })
}

// 新增得分点
const handelscoreCancel = () => {
  editabDataChead.value.pySzDfdList.push({
    contents: '',
    dfdScore: 0,
    sortNum: editabDataChead.value.pySzDfdList.length + 1,
    stId: props.isBatchHasObj.id,
    id: +new Date(),
  })
}

/**
 * 数据字典
 * @param { String } groupCode 字典组编码
 */
import { getDictionaryList } from '/@/views/teacher/home/index'

watch(
  () => props.isBatchHasObj,
  async val => {
    if (!val.id) return
    if (machineReadableProblem.includes(props.isBatchHasObj.tmlx)) {
      teacherOptions.value = [
        {
          label: props.chartObj.pyzzName,
          value: props.chartObj.pyzzAccount,
        },
      ]
      editabDataChead.value.pySzJsfpAccountList = [props.chartObj.pyzzAccount]
    } else {
      teacherOptions.value = []
      getTeacherOptions('')
    }
    let { code, data } = await reviewGetPySzInfoByStId({
      stId: val.id,
      kmdm: props.kmdm,
    })
    if (code == 200) {
      pySzInfoVO.value = data[0] || {}
    }
    if (pySzInfoVO.value.pySzId) {
      editabDataChead.value = cloneDeep(pySzInfoVO.value)
      editabDataChead.value.pySzJsfpAccountList =
        pySzInfoVO.value.pySzJsfpList?.map(e => e.account) || []
    }
    editabDataChead.value.tmfz = val.tmfz
    editabDataChead.value.pySzCkdaInfoList = []

    if (val.children && val.children.length) {
      let loadList: any = []
      for (let i = 0; i < val.children.length; i++) {
        let filterArr: any = {}
        if (pySzInfoVO.value.pySzId && pySzInfoVO.value.pySzCkdaList.length) {
          filterArr = pySzInfoVO.value.pySzCkdaList.find(e => val.children[i].id == e.stId) || {}
          if (filterArr.ckda && val.tmlx == '多项选择题') {
            filterArr.ckda = filterArr.ckda.split(',')
          }
        }
        loadList.push({
          stId: val.children[i].id, //试题id
          ckda: '', //答案信息
          tmfz: val.children[i].tmfz, //试题分值
          name: `${val.children[i].tmbh}${+val.children[i].tmbt || ''}`,
          ckdaOptions:
            val.tmlx == '多项选择题' || val.tmlx == '单项选择题'
              ? isJdWrongType.slice(0, val.children[i].xxsl)
              : val.tmlx == '判断题'
              ? isJdWrongType.slice(isJdWrongType.length - 2)
              : [],
          ...filterArr,
        })
      }
      function updateAnimation() {
        if (loadList.length) {
          editabDataChead.value.pySzCkdaInfoList.push(
            ...loadList.splice(0, loadList.length > 10 ? 10 : loadList.length)
          )
          requestAnimationFrame(updateAnimation)
        }
      }
      requestAnimationFrame(updateAnimation)
    } else {
      let pySzCkdaInfo: any = {}
      if (pySzInfoVO.value.pySzId && pySzInfoVO.value.pySzCkdaList.length) {
        pySzCkdaInfo = pySzInfoVO.value.pySzCkdaList[0]
      }
      editabDataChead.value.pySzCkdaInfoList.push({
        stId: val.id, //试题id
        ckda: '', //答案信息
        tmfz: val.tmfz, //试题分值
        ...pySzCkdaInfo,
        name: `${val.tmbh}${val.tmbt || ''} '参考答案'`,
      })
    }
  },
  { deep: true, immediate: true }
)

function previewImg(event: any) {
  if (event?.target.tagName == 'IMG') {
    createImgPreview({
      imageList: [event.target.src],
    })
  }
}

onMounted(async () => {
  await getDictionaryList('dxlxScoreType', dxlxOptions)
  await getDictionaryList('pyMs', pymsOptions)
})
</script>

<style lang="less" scoped>
.cancel-form {
  padding: 20px 20px 20px 20px;
  height: 100%;
  overflow-y: auto;

  ::v-deep(.ant-table-cell) {
    .ant-form-item {
      margin-bottom: 0;
    }
  }
}

.cancel-form-item {
  flex-direction: column;
  ::v-deep(.ant-form-item-label) {
    text-align: left;
    padding: 0 0 8px;
    line-height: 1.5715;
    white-space: initial;
  }

  ::v-deep(.ant-form-item-control) {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    min-height: auto;
  }
}
</style>
